<template>
  <div class="user-tools">
    <van-cell title="收货地址" is-link to="address?type=edit" />
    <van-cell title="退出登录" is-link @click="logout" />
    <!-- <van-cell title="上传收款码" is-link @click="updateSelfQRCode" /> -->
    <van-cell title="生成邀请码" is-link @click="generateQRCode" />
    <!-- <van-cell title="消息列表" is-link to="words" /> -->
    <van-overlay
      ref="imageDom"
      :show="qrcodeShow"
      class="qrcode-overlay"
      :custom-style="{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }"
      :style="qrcodeShow ? {} : { display: 'none' }"
      @click="changeQrcodeShow"
      @touchstart="gtouchstart()"
      @touchmove="gtouchmove()"
      @touchend="showDeleteButton()"
    >
      <div class="overlay-username" :style="this.position.title">
        {{ userInfo.userRealName }}
      </div>
      <div class="overlay-inviteCode" :style="this.position.invote">
        {{ userInfo.inviteCode }}
      </div>
      <!-- <div class="overlay-inviteCode"  @click="">
        保存二维码
      </div> -->
      <div class="wrapper" :style="this.position.img" @click.stop>
        <div ref="qrcode" class="qrcode" />
      </div>
    </van-overlay>
    <div v-if="qrcodeShow" class="overlay-inviteCode btn" :style="this.position.invoteSave">长按去预览图片</div>

    <van-dialog v-model="showPaymentVisible" title="收款二维码" show-cancel-button @confirm="confirmPay">
      <div
        style="
          display: flex;
          justify-content: center;
          width: 100%;
          margin-top: 20px;
        "
      >
        <van-uploader v-model="uploader" multiple :max-count="1" :after-read="afterRead" preview-size="6.9rem" />
      </div>
    </van-dialog>
    <van-image-preview
      v-model="ImageShow"
      :images="imagesUrl"
      :lazyLoad="true"
    >
    </van-image-preview>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import { mapGetters } from 'vuex'
import { delUserInfo } from '@/utils/localStorage'
import QRCode from 'qrcodejs2'
import { base64uploadFile } from '@/api/upload'
import { userSelfQrCode } from '@/api/cart'
import { getWords } from '@/api/user'
import html2canvas from 'html2canvas'
export default {
  data() {
    return {
      qrcodeShow: false,
      text: '',
      qrcode: null,
      showPaymentVisible: false,
      uploader: [],
      urls: '',
      imagesUrl:[],
      ImageShow:false,
      position: {
        title: {
          left: '',
          top: ''
        },
        invote: {
          left: '',
          top: ''
        },
        img: {
          bottom: '',
          right: ''
        },
        invoteSave: {
          left: '',
          top: ''
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() { },
  methods: { // 长按事件（起始）
    gtouchstart(item) {
      var self = this
      this.timeOutEvent = setTimeout(function() {
        self.longPress(item)
      }, 500) // 这里设置定时器，定义长按500毫秒触发长按事件
      return false
    },
    // 手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
    showDeleteButton(item) {
      clearTimeout(this.timeOutEvent) // 清除定时器
      if (this.timeOutEvent != 0) {
        // 这里写要执行的内容（如onclick事件）
        console.log('点击但未长按')
      }
      return false
    },
    // 如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
    gtouchmove() {
      clearTimeout(this.timeOutEvent) // 清除定时器
      this.timeOutEvent = 0
    },
    // 真正长按后应该执行的内容
    longPress(val) {
      this.timeOutEvent = 0
      // 执行长按要执行的内容，如弹出菜单
      console.log('长按')
      this.$dialog.confirm({
        title: '系统提示',
        message: '去预览保存图片'
      }).then(() => {
        this.downImg()
      })
    },
    changeQrcodeShow() {
      this.qrcodeShow = false
    },
    autoPosition() {
      const basic = 560
      const bodyWidth = document.body.clientWidth

      const scale = bodyWidth / basic
      // const scale = 0.5

      console.log('scale',scale)
      let titleLeft = 168
      let titleTop = 188
      let titleWidth = 128
      let titleFont = 24

      titleLeft = scale * titleLeft + 'px'
      titleTop = scale * titleTop + 'px'
      titleWidth = scale * titleWidth + 'px'
      titleFont = scale * titleFont + 'px'
      this.$set(this.position, 'title', {
        left: titleLeft,
        top: titleTop,
        width: titleWidth,
        fontSize: titleFont
      })

      let invoteLeft = 168
      let invoteTop = 810
      let invoteWidth = 128
      let invoteFont = 19.2

      invoteLeft = scale * invoteLeft + 'px'
      invoteTop = scale * invoteTop + (scale * invoteFont) / 2 + 'px'
      invoteWidth = scale * invoteWidth + 'px'
      invoteFont = scale * invoteFont + 'px'

      this.$set(this.position, 'invote', {
        left: invoteLeft,
        top: invoteTop,
        width: invoteWidth,
        fontSize: invoteFont
      })

      let invoteSaveLeft = 168
      let invoteSaveTop = 730
      let invoteSaveWidth = 228
      let invoteSaveFont = 30.2

      invoteSaveLeft = scale * invoteSaveLeft + 'px'
      invoteSaveTop = scale * invoteSaveTop + (scale * invoteSaveFont) / 2 + 'px'
      invoteSaveWidth = scale * invoteSaveWidth + 'px'
      invoteSaveFont = scale * invoteSaveFont + 'px'

      this.$set(this.position, 'invoteSave', {
        position: 'fixed',
        zIndex: '9999',
        left: invoteSaveLeft,
        top: invoteSaveTop,
        width: invoteSaveWidth,
        fontSize: invoteSaveFont
      })

      let imgLeft = 306
      let imgTop = 780
      const imgWidth = 256
      let imgScale = 0.5
      imgScale = scale * imgScale
      imgLeft = scale * imgLeft + 'px'
      imgTop = scale * imgTop + 'px'
      // imgTop = scale * imgTop - (imgWidth * imgScale) / 2 + "px";
      // imgWidth = scale * imgWidth + "px";
      // imgScale = 1;
      this.$set(this.position, 'img', {
        left: imgLeft,
        top: imgTop,
        transform: `scale(${imgScale})`
      })
      console.log(this.position)
    },
    async confirmPay() {
      await userSelfQrCode({ url: this.urls })
      this.showPaymentVisible = false
      this.$router.go(0)
    },
    async afterRead(file) {
      this.$toast.loading({
        message: '正在上传...',
        forbidClick: true,
        overlay: true
      })
      // 此时可以自行将文件上传至服务器
      const uploadRes = await base64uploadFile({
        base64content: file.content,
        filename: file.file.name
      })
      this.urls = uploadRes.map.fileName
      this.$toast.clear()
      this.$toast.success('上传图片成功')
    },
    updateSelfQRCode() {
      if (this.userInfo.selfQrCode != null) {
        // debugger;
        console.log(`${location.origin}/upload/${this.userInfo.selfQrCode}`)
        this.uploader = [
          {
            url: `${location.origin}/upload/${this.userInfo.selfQrCode}`,
            deletable: true,
            imageFit: 'contain',
            previewSize: 120
          }
        ]
      }

      this.showPaymentVisible = true
    },
    generateQRCode() {
      const host = location.origin
      this.text = `${host}/#/registry?inviteCode=${this.userInfo.inviteCode}`
      this.autoPosition()
      if (this.qrcode != null) {
        this.qrcode = null // 清除原来的二维码
        this.$refs.qrcode = null
      }
      this.qrcodeShow = true
      const basic = 560
      const bodyWidth = document.body.clientWidth
      const scale = bodyWidth / basic
      this.qrcode = new QRCode(this.$refs.qrcode, {
        width: 256,
        height: 256,
        text: this.text,
      })
    },
    downImg(e) {
      // event.stopPropagation();
      const qrcodeImageSrc = this.$refs.qrcode.getElementsByTagName('img')[0].src
      console.log('qrcodeImageSrc:', qrcodeImageSrc)
      this.downloadImageFromBase64(qrcodeImageSrc, '二维码')
    },
    downloadImageFromBase64(base64String, fileName) {
      console.log('this.$refs.imageDom:', this.$refs.imageDom)
      html2canvas(this.$refs.imageDom).then(async canvas => {
        // 转成图片，生成图片地址
        const imgUrl = canvas.toDataURL('image/png')
        // const binaryData = atob(imgUrl.split(',')[1])
        // const arrayBuffer = new ArrayBuffer(binaryData.length)
        // const uint8Array = new Uint8Array(arrayBuffer)
        // for (let i = 0; i < binaryData.length; i++) {
        //   uint8Array[i] = binaryData.charCodeAt(i)
        // }

        // const blob = new Blob([uint8Array], { type: 'application/octet-stream' })

        // // 3. 创建一个 URL 对象
        // const url = window.URL.createObjectURL(blob)
        const name = this.userInfo.id+''+new Date().getTime()+'.png'
        const uploadRes = await base64uploadFile({
          base64content: imgUrl,
          filename: name
        })

        this.imagesUrl.push(uploadRes.map.url) 
        this.ImageShow = true
        // this.imgdown(uploadRes.map.url,name)
        // 4. 创建一个 <a> 标签,并设置 download 属性
        // const link = document.createElement('a')
        // // link.setAttribute('href', uploadRes.map.url)
        // link.url =  uploadRes.map.url
        // link.download= name 

        // 4. 创建一个 <a> 标签,并设置 download 属性
        // const link = document.createElement('a')
        // // link.setAttribute('href', uploadRes.map.url)
        // link.url =  uploadRes.map.url
        // link.download= name 

        // // 5. 模拟点击 <a> 标签,触发下载
        // document.body.appendChild(link)
        // link.click()
        // document.body.removeChild(link)
      })
    },
    imgdown(imgSrc,name){

      saveAs(imgSrc, name)


      // let xmlhttp = new XMLHttpRequest();
      //     xmlhttp.open("GET", imgSrc, true);
      //     xmlhttp.responseType = "blob";
      //     xmlhttp.onload = function () {
      //       if (this.status == 200) {
      //         const blob = this.response;
      //         const link = document.createElement("a");
      //         link.href = window.URL.createObjectURL(blob);
      //         // link.download = url.substring(url.lastIndexOf("/") + 1, url.length);
      //         link.download = name;
      //         //此写法兼容可火狐浏览器
      //         document.body.appendChild(link);
      //         const evt = document.createEvent("MouseEvents");
      //         evt.initEvent("click", false, false);
      //         link.dispatchEvent(evt);
      //         window.URL.revokeObjectURL(link.href);
      //         document.body.removeChild(link);
      //       }
      //     };
      //     xmlhttp.send();



      // const img =new Image()
      // img.setAttribute('crossOrigin','anonymous')
      // img.onload = function(){
      //   var canvas = document.createElement("canvas")
      //   canvas.width = img.width
      //   canvas.height = img.height
      //   var context =canvas.getContext('2d')
      //   context.drawImage(img,0,0,img.width,img.height)
      //   var url = canvas.toDataURL("image/png")
      //   const link = document.createElement('a')
      //   var event = new MouseEvent("click")
      //   // link.setAttribute('href', uploadRes.map.url)
      //   link.url = url
      //   link.download= name || "photo"
      //   link.dispatchEvent(event)
      // }
      // img.src = imgSrc
    },
    logout() {
      this.$store.dispatch('user/logout').then(() => {
        delUserInfo()
        this.$notify({
          type: 'success',
          message: '退出成功',
          duration: 2000,
          onOpened: () => {
            this.$router.push({ name: 'Login' })
          }
        })
      })
    }
  }
}
</script>

<style>
:root {
  --user-tools-shadow: 0px 2px 16px 0px rgba(0, 0, 0, 0.09);
}
</style>

<style lang="scss" scoped>
.qrcode-overlay {
  width: 100vw;
  height: 100vh;
  background-image: url("./qrcode-bg.png");
  background-size: 100vw auto;
  background-repeat: no-repeat;
  background-color: #c90700;
  -webkit-touch-callout: default !important;
  -webkit-user-select: none;
  z-index: 99;

  .overlay-username {
    position: absolute;
    left: 10.5rem;
    top: 11.8rem;
    width: 8rem;
    color: white;
    font-size: 1.5rem;
    text-align: center;
  }

  .overlay-inviteCode {
    position: absolute;
    left: 10.5rem;
    bottom: 6.3rem;
    width: 8rem;
    font-size: 1.2rem;
    text-align: center;

  }

}

.wrapper {
  position: absolute;
  width: 256px;
  height: 256px;
  bottom: -1rem;
  right: 3rem;
  transform-origin: top left;
  transform: scale(0.5);

  // transform-origin: center;
  .qrcode {}
}

.user-tools {
  width: 702px;
  background: rgba(255, 255, 255, 1);
  margin: 0 auto;
  margin-top: 24px;
  box-shadow: var(--user-tools-shadow); // 这里使用 css 函数，是为了避免旧版本 vue-cli 依赖的 css 压缩工具（mini-css-extract-plugin）导致的 bug
  border-radius: 24px;
  overflow: hidden;
}
</style>
